package com.zznj.xzjc.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;

import com.zznj.xzjc.R;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.util.List;

public class FileUtils {


	public static final String ROOT_PATH = Environment.getExternalStorageDirectory()+"/com.zznj.xzjc/cache/video/";
	//判断是否安装SDCard
	public static boolean isSdOk(){
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			return true;
		}
		return false;
	}
	//创建一个文件夹，用来存放下载的文件
	public static File getRootFile(){
		File rootFile = new File(ROOT_PATH);
		if (!rootFile.exists()){
			rootFile.mkdirs();
		}
		return rootFile;
	}

	public static File getFinishFile(String name){
		String path = ROOT_PATH+name.replace("mp4","");
		File rootFile = new File(path);
		return rootFile;
	}

	public static boolean isDownLoadSuccess(String urlPath){
		String path = ROOT_PATH+urlPath.substring(urlPath.lastIndexOf("/") + 1).replace("mp4","");;
		File rootFile = new File(path);
		return rootFile.exists();
	}

	public static Options getBitmapOption(int inSampleSize){
        System.gc();
        Options options = new Options();
        options.inPurgeable = true;
        options.inSampleSize = inSampleSize;
        return options;
	}

	public static String getPath(Context context, Uri uri) {

		if ("content".equalsIgnoreCase(uri.getScheme())) {
			String[] projection = { "_data" };
			Cursor cursor = null;

			try {
				cursor = context.getContentResolver().query(uri, projection, null, null, null);
				int column_index = cursor.getColumnIndexOrThrow("_data");
				if (cursor.moveToFirst()) {
					return cursor.getString(column_index);
				}
			} catch (Exception e) {
			}
		}

		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}

	public static void deleteFile(File file) {
		if (file.isFile()) {
			file.delete();
		} else {
			if (file.isDirectory()) {
				File[] childfiles = file.listFiles();
				for (File f : childfiles) {
					deleteFile(f);
				}
				file.delete();
			}
		}
	}

	public static boolean haveCache(File file) {
		if (!file.exists()) {
			return false;
		} else {
			if (file.isDirectory()) {
				File[] childfile = file.listFiles();
				if (childfile == null || childfile.length == 0) {
					return false;
				} else {
					return true;
				}
			} else {
				return true;
			}
		}
	}

	/**
	 * ��ȡ�ļ��д�С
	 * 
	 * @param f
	 * @return
	 * @throws Exception
	 */
	public static long getFileSizes(File f) throws Exception {
		long size = 0;
		File flist[] = f.listFiles();
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size = size + getFileSizes(flist[i]);
			} else {
				size = size + getFileSize(flist[i]);
			}
		}
		return size;
	}

	private static long getFileSize(File file) throws Exception {
		long size = 0;
		if (file.exists()) {
			FileInputStream fis = null;
			fis = new FileInputStream(file);
			size = fis.available();
		} else {
			file.createNewFile();
		}
		return size;
	}

	public static String FormetFileSize(long fileS) {
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		String wrongSize = "0B";
		if (fileS == 0) {
			return wrongSize;
		}
		if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "KB";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "MB";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "GB";
		}
		return fileSizeString;
	}

	private static String[][] MIME_MapTable = {
			{ ".3gp", "video/3gpp" }, { ".apk", "application/vnd.android.package-archive" }, { ".asf", "video/x-ms-asf" }, { ".avi", "video/x-msvideo" }, { ".bin", "application/octet-stream" }, { ".bmp", "image/bmp" }, { ".c", "text/plain" }, { ".class", "application/octet-stream" }, { ".conf", "text/plain" }, { ".cpp", "text/plain" }, { ".doc", "application/msword" },
			{ ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }, { ".xls", "application/vnd.ms-excel" }, { ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }, { ".exe", "application/octet-stream" }, { ".gif", "image/gif" }, { ".gtar", "application/x-gtar" }, { ".gz", "application/x-gzip" }, { ".h", "text/plain" },
			{ ".htm", "text/html" }, { ".html", "text/html" }, { ".jar", "application/java-archive" }, { ".java", "text/plain" }, { ".jpeg", "image/jpeg" }, { ".jpg", "image/jpeg" }, { ".js", "application/x-javascript" }, { ".log", "text/plain" }, { ".m3u", "audio/x-mpegurl" }, { ".m4a", "audio/mp4a-latm" }, { ".m4b", "audio/mp4a-latm" }, { ".m4p", "audio/mp4a-latm" },
			{ ".m4u", "video/vnd.mpegurl" }, { ".m4v", "video/x-m4v" }, { ".mov", "video/quicktime" }, { ".mp2", "audio/x-mpeg" }, { ".mp3", "audio/x-mpeg" }, { ".mp4", "video/mp4" }, { ".mpc", "application/vnd.mpohun.certificate" }, { ".mpe", "video/mpeg" }, { ".mpeg", "video/mpeg" }, { ".mpg", "video/mpeg" }, { ".mpg4", "video/mp4" }, { ".mpga", "audio/mpeg" },
			{ ".msg", "application/vnd.ms-outlook" }, { ".ogg", "audio/ogg" }, { ".pdf", "application/pdf" }, { ".png", "image/png" }, { ".pps", "application/vnd.ms-powerpoint" }, { ".ppt", "application/vnd.ms-powerpoint" }, { ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" }, { ".prop", "text/plain" }, { ".rc", "text/plain" },
			{ ".rmvb", "audio/x-pn-realaudio" }, { ".rtf", "application/rtf" }, { ".sh", "text/plain" }, { ".tar", "application/x-tar" }, { ".tgz", "application/x-compressed" }, { ".txt", "text/plain" }, { ".wav", "audio/x-wav" }, { ".wma", "audio/x-ms-wma" }, { ".wmv", "audio/x-ms-wmv" }, { ".wps", "application/vnd.ms-works" }, { ".xml", "text/plain" }, { ".z", "application/x-compress" },
			{ ".zip", "application/x-zip-compressed" }, { "", "*/*" } };


	public static String getMIMEType(String fName) {

		String type = "*/*";
		int dotIndex = fName.lastIndexOf(".");
		if (dotIndex < 0) {
			return type;
		}
		String end = fName.substring(dotIndex, fName.length()).toLowerCase();
		if (end == "")
			return type;
		for (int i = 0; i < MIME_MapTable.length; i++) {
			if (end.equals(MIME_MapTable[i][0]))
				type = MIME_MapTable[i][1];
		}
		return type;
	}

	public static void openFile(Context context, File file) {
		String type = getMIMEType(file.getName());
		Intent sharingIntent = new Intent(Intent.ACTION_VIEW);
		sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		sharingIntent.setDataAndType(Uri.fromFile(file), type);
		PackageManager packageManager = context.getPackageManager();
		List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(sharingIntent, PackageManager.MATCH_DEFAULT_ONLY);
		int i = 0;
		while (i < resolveInfo.size()) {
			System.out.println(i + "  " + resolveInfo.get(i).activityInfo.packageName);
			if (resolveInfo.get(i).activityInfo.packageName.equals("com.tencent.mobileqq")) {
				resolveInfo.remove(resolveInfo.get(i));
			}
			i++;
		}
		if (resolveInfo.size() == 0) {
		} else {
		}
	}

	public static int getIcon(String fileName) {
		String str = fileName.substring(fileName.lastIndexOf(".") + 1);
		String image = "jpg,jpeg,png,gif";
		String pdf = "pdf";
		String xls = "xls,xlsx";
		String doc = "doc,docx";
		String ppt = "ppt,pptx";
		String movie = "mp4,avi,3gp,rmvb,wmv,mkv,mpg,vob,mov,flv";
		String music = "MP3,WMA,WAV,OGG,APE";
		String zip = "rar,zip";
		String txt = "txt";
		if (str != null && !"".equals(str)) {
			if (image.contains(str)) {
				return R.mipmap.icon_file_pic;
			} else if (pdf.contains(str)) {
				return R.mipmap.icon_file_pdf;
			} else if (xls.contains(str)) {
				return R.mipmap.icon_file_xls;
			} else if (ppt.contains(str)) {
				return R.mipmap.icon_file_ppt;
			} else if (doc.contains(str)) {
				return R.mipmap.icon_file_doc;
			} else if (movie.contains(str)) {
				return R.mipmap.icon_file_video;
			} else if (music.toLowerCase().contains(str.toLowerCase())) {
				return R.mipmap.icon_file_amr;
			} else if (zip.contains(str)) {
				return R.mipmap.icon_file_zip;
			} else if (txt.contains(str)) {
				return R.mipmap.icon_file_txt;
			} else {
				return R.mipmap.icon_file_other;
			}
		} else {
			return R.mipmap.icon_file_other;
		}
	}

	public static Drawable getApkIcon(Context context, String apkPath) {
		PackageManager pm = context.getPackageManager();
		PackageInfo info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
		if (info != null) {
			ApplicationInfo appInfo = info.applicationInfo;
			appInfo.sourceDir = apkPath;
			appInfo.publicSourceDir = apkPath;
			try {
				return appInfo.loadIcon(pm);
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}